<?php

declare (strict_types = 1);

namespace app\certificate\controller\admin\v1\digitalMachine;

use libs\ALiOss;
use libs\Image;
use think\facade\Db;
use think\Request;

class Type
{
    public $table = "certificate_digitalmachinetype";
    /**
     * @Description:
     * @param {Request} $request
     */
    public function getList(Request $request)
    {
        $data  = $request->data;
        $limit = $data['limit'] ?? 10;
        $page  = $data['page'] ?? 1;
        $where = [
            ['isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
        }
        if (!empty($request->authWhere['projectCode'])) {
            array_push($where, ['projectCode', '=', $request->authWhere['projectCode']]);
        }
        if (!empty($data['name'])) {
            array_push($where, ['name', 'like', "%" . $data['name'] . "%"]);
        }
        
        $data = DB::table($this->table)
            ->where($where)
            // ->page((int) $page, (int) $limit)
            ->field(['name', 'uuid','level','pUuid'])
            ->order(['level','id'=>'desc'])
            ->select()->toArray();
        $processData = [];
        foreach ($data as $key => $value) {
            if($value['level'] == 1){
                $uuid = $value['uuid'];
                unset($value['pUuid']);
                $processData[$uuid] = $value;
                $processData[$uuid]['children'] = [];
            }else{
                $pUuid = $value['pUuid'];
                unset($value['pUuid']);
                $processData[$pUuid]['children'][] = $value;
            }
            
        }
        $list = [];
        foreach ($processData as $key => $value) {
            $list[] = $value;
        }
        // $count = DB::table($this->table)
        //     ->where($where)
        //     ->count('id');

        $data = [
            'list'  => $list,
            // 'count' => $count,
        ];
        return result(SUCCESS, $data, '');
    }
    /**
     * @Description: 添加
     * @param {Request} $request
     */
    public function create(Request $request)
    {

        $data                = $request->data;
        $data['uuid']        = createUuid();
        $data['projectCode'] = $request->authWhere['projectCode'] ?? "";
        $data['corpCode']    = $request->corpCode;
        $data['isDelete']    = 0;
        $data['pUuid'] = $data['type'] ?? '';
        unset($data['type']);
        $data['level'] = ((int)!empty($data['pUuid'])) + 1 ;
        $where               = [
            ['isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
        }
        // $check = DB::table($this->table)->where($where)->where([
        //     ['name', '=', $data['name']],
        //     ['is', '=', $data['is']],
        // ])->value('id');
        // if ($check) {
        //     return result(FAIL, '', '设备类型名称已存在,无法添加!');
        // }
        $checkStatus = $this->checkUuidIsExist($data, $request);
        if ($checkStatus) {
            return result(FAIL, '', $checkStatus);
        }
        $data['qrCode']      = $this->qrCode($data['projectCode'], $data['uuid'], $data['name']);
        DB::startTrans();
        try {
            //添加设备类型
            DB::table($this->table)->insert($data);
            DB::commit();
            $data['inDate'] = date('Y-m-d', time());
            return result(SUCCESS, $data, '添加成功');
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
        }
        return result(FAIL, '', '添加失败,请重试');
    }
    /**
     * @Description: 修改
     * @Author: Terry
     * @Date: 2024-01-31 21:02:26
     */
    public function update(Request $request)
    {
        $data  = $request->data;
        $uuid  = $data['uuid'];
        $check = $this->accordUuidGetData($this->table, $uuid, 'uuid', $request);
        if (empty($check)) {
            return result(FAIL, '', '设备类型不存在,无法修改!');
        }
        $where = [
            ['isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
        }
        if (!empty($request->authWhere['projectCode'])) {
            array_push($where, ['projectCode', '=', $request->authWhere['projectCode']]);
        }
        // $check = DB::table($this->table)->where($where)->where([
        //     ['uuid', '<>', $uuid],
        //     ['name', '=', $data['name']],
        // ])->value('id');
        // if ($check) {
        //     return result(FAIL, '', '设备类型名称已存在,无法修改!');
        // }

        $oldName = DB::table($this->table)->where($where)->where([
            ['uuid', '=', $uuid],
        ])->value('name');
        if (!$oldName) {
            return result(FAIL, '', '设备类型已被删除,无法修改!');
        }
        $checkStatus = $this->checkUuidIsExist($data, $request);
        if ($checkStatus) {
            return result(FAIL, '', $checkStatus);
        }

        $updateData = [
            'name'                      => $data['name'],
            'subtitle'                  => isset($data['subtitle']) ? $data['subtitle'] : '',
            'repairTypeUuid'            => isset($data['repairTypeUuid']) ? $data['repairTypeUuid'] : '',
            'machineRiskTypeUuid'       => isset($data['machineRiskTypeUuid']) ? $data['machineRiskTypeUuid'] : '',
            'heavyMachineCheckTypeUuid' => isset($data['heavyMachineCheckTypeUuid']) ? $data['heavyMachineCheckTypeUuid'] : '',
            'remark'                    => $data['remark'] ?? '',
            'pUuid'                    =>  $data['type'] ?? '',
        ];
        $return = [];
        if ($data['name'] != $oldName ) {
            $text                 = $data['name'];
            $updateData['qrCode'] = $this->qrCode($request->authWhere['projectCode'], $data['uuid'], $text);
            $return               = ['qrCode' => $updateData['qrCode']];
        }

        DB::table($this->table)->where($where)->where('uuid', $uuid)->update($updateData);
        return result(SUCCESS, $updateData, '保存成功');
    }

    public function destroy(Request $request)
    {
        $data  = $request->data;
        $where = [
            ['isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
        }
        if (!empty($request->authWhere['projectCode'])) {
            array_push($where, ['projectCode', '=', $request->authWhere['projectCode']]);
        }
        DB::table($this->table)->where($where)->where('uuid', $data['uuid'])->update([
            'isDelete' => 1,
        ]);
        return result(SUCCESS, '', '删除成功');
    }

    public function checkUuidIsExist($data, $request)
    {

        //用于create和update
        $array = [
            "certificate_flow"                  => 'repairTypeUuid' . "||检修类型唯一码不存在",
            "certificate_heavymachinechecktype" => 'heavyMachineCheckTypeUuid' . "||设备许可证类型唯一码不存在",
            "certificate_machinerisktype"       => 'machineRiskTypeUuid' . "||重型检查类型唯一码不存在",
        ];
        $checkMsg = '';
        foreach ($array as $key => $value) {
            $table = $key;
            $d     = explode("||", $value);
            $uuid  = $d[0];
            $msg   = $d[1];
            if(!isset($data[$uuid]) || empty($data[$uuid])) continue;
            $check = $this->accordUuidGetData($table, $data[$uuid], 'uuid', $request);
            if (empty($check)) {
                $checkMsg = $msg;
                break;
            }
        }

        return $checkMsg;
    }

    /**
     * @Descripttion:二维码生成
     * @name: qrCode
     * @param {*} $uuid
     */
    private function qrCode($prjCode, $uuid, $text)
    {
        $file   = "image/qrcode/{$prjCode}";
        $name   = time() . rand(0, 99999) . '.jpg';
        $path   = "packageC/pages/certificate/machineDigitization/create/create?uuid={$uuid}";
        $qrCode = createQrCode($path, $name, $file);
        if (!$qrCode) {
            return false;
        }

        $img  = new image();
        $path = $img->imgButtomAddText($qrCode, $text);

        $exp  = explode('.', $path);
        $oss  = new ALIOss($exp[0], $exp[1]);
        $path = $oss->upload($path);

        return $path;
    }

    /**
     * @Description: 获取数据
     * @param {Request} $request
     */
    public function getDetail(Request $request)
    {
        $data = $request->data;
        $uuid = $data['uuid'];

        $where = [
            ['isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
        }
        if (!empty($request->authWhere['projectCode'])) {
            array_push($where, ['projectCode', '=', $request->authWhere['projectCode']]);
        }
        $data = DB::table($this->table)->where($where)->where('uuid', $uuid)->field(['inDate', 'corpCode', 'name', 'remark', 'uuid', 'qrCode', 'repairTypeUuid', 'machineRiskTypeUuid', 'heavyMachineCheckTypeUuid', 'subtitle','pUuid as type','level'])->find();
        if (empty($data)) {
            return result(SUCCESS, [], '');
        }
    
        list($data['repairTypeName'], $data['repairTypeUuid']) = $this->getNameAndValidateUuid('certificate_flow', $data['repairTypeUuid'], $request);
        list($data['heavyMachineCheckTypeName'], $data['heavyMachineCheckTypeUuid']) = $this->getNameAndValidateUuid('certificate_heavymachinechecktype', $data['heavyMachineCheckTypeUuid'], $request);
        list($data['machineRiskTypeName'], $data['machineRiskTypeUuid']) = $this->getNameAndValidateUuid('certificate_machinerisktype', $data['machineRiskTypeUuid'], $request);

        return result(SUCCESS, $data, '');
    }

    // 定义一个函数来处理UUID和名称的获取与检验
    protected function getNameAndValidateUuid($type, $uuid, $request) {
        $name = $this->accordUuidGetData($type, $uuid, 'name', $request);
        if ($name == '') {
            $uuid = ''; // 如果名称为空，则将UUID清空
        }
        return [$name, $uuid]; // 返回名称和可能修改过的UUID
    }

    protected function accordUuidGetData($table = '', $uuid = '', $fileName = '', $request)
    {
        $where = [
            ['isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
        }
        if (!empty($request->authWhere['projectCode'])) {
            array_push($where, ['projectCode', '=', $request->authWhere['projectCode']]);
        }
        $data = DB::table($table)->where($where)->where('uuid', $uuid)->field(["{$fileName}"])->find();
        return $data["{$fileName}"] ?? '';
    }
    public function getThreeOptions(Request $request)
    {
        $data  = $request->data;
        $where = [
            ['isDelete', '=', 0],
            ['projectCode', '=', $request->prjCode],

        ];
        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
        }
        $pTypeList = DB::table($this->table)
        ->where($where)
        ->where('level',1)
        ->field(['name','uuid'])
        ->select();
        $flowList = DB::table('certificate_flow')
            ->where($where)
            ->where('name','檢修流程')
            ->field(['name', 'remark', 'inDate', 'uuid'])
            ->order('id desc')
            ->select();
        $machineRiskTypeList = DB::table('certificate_machinerisktype')
            ->where($where)
            ->field(['name', 'remark', 'inDate', 'uuid'])
            ->order('id desc')
            ->select();
        $heavy = DB::table('certificate_heavymachinechecktype')
            ->where($where)
            ->field(['name', 'remark', 'inDate', 'uuid'])
            ->order('id desc')
            ->select();

        $list = [
            'flowList'                  => $flowList,
            'machineRiskTypeList'       => $machineRiskTypeList,
            'heavyMachineCheckTypeList' => $heavy,
            'pTypeList' => $pTypeList,
        ];
        return result(SUCCESS, $list, '');
    }

}
